﻿using JXCModel;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace JXCDAL
{/// <summary>
    /// DAL类父类
    /// </summary>
    public class BaseDAL<T> where T : class,new()
    {
        protected List<T> GetAll()
        {
            JXCEntities db = new JXCEntities();  //上下文对象
            return db.Set<T>().ToList();
        }

        protected int Add(T info)
        {
            JXCEntities db = new JXCEntities();
            db.Set<T>().Add(info);
            return db.SaveChanges();
        }

        protected int Update(T info)
        {
            JXCEntities db = new JXCEntities();
            db.Entry<T>(info).State = EntityState.Modified;
            return db.SaveChanges();
        }

        protected int Delete(object pk)
        {
            JXCEntities db = new JXCEntities();
            T info = db.Set<T>().Find(pk);
            if (info != null)
            {
                db.Set<T>().Remove(info);
                return db.SaveChanges();
            }
            else
            {
                return 0;
            }
        }


        protected List<T> Where(Expression<Func<T, bool>> where)
        {
            JXCEntities db = new JXCEntities();
            //不缓存
            return db.Set<T>().AsNoTracking().Where(where).ToList();
        }

        /// <summary>
        /// 根据主键查询，返回一个实体类
        /// </summary>
        /// <param name="pk"></param>
        /// <returns></returns>
        protected virtual T GetByPK(object pk)
        {
            JXCEntities db = new JXCEntities();
            T info = db.Set<T>().Find(pk);
            return info;

        }
    }
}
